package com.bwie.gateway.filters;

import com.alibaba.fastjson.JSONObject;
import com.bwie.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
@Configuration
@Log4j2
public class GlobalExceptionHandler {

    /**
     * 全局的异常处理
     * @param exception
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<String> runtimeException(MethodArgumentNotValidException exception){
        return Result.error(
                JSONObject.toJSONString(
                        exception.getBindingResult().getAllErrors()
                                .stream()
                                .map(ObjectError::getDefaultMessage)
                                .collect(Collectors.toList())
                )
        );
    }

@ExceptionHandler(value = IllegalArgumentException.class)
    public Result<String> illegalArgumentExceptionHandler(IllegalArgumentException exception){
        log.error("请求异常：[{}]", exception.getMessage(), exception);
        return Result.error(exception.getMessage());
    }

}
